package com.peng.community.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Slf4j
@Component
public class MailClient {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    public void sendMail(String to, String subject,String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
//        帮助将属性设置到message的对象
            MimeMessageHelper messageHelper = new MimeMessageHelper(message);
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            //true表示支持html类型的邮件内容
            messageHelper.setText(content,true);

            mailSender.send(message);
        } catch (MessagingException e) {
            log.error("发送邮件失败:{}", e.getMessage());
        }

    }
}
